import time
from django.apps import AppConfig
import subprocess
import psutil
from elasticsearch import Elasticsearch
import platform


class MyAppConfig(AppConfig):
    name = 'celery_tasks'

    def ready(self):
        # 在Django启动时检测并启动Celery
        if not is_celery_running():
            start_celery()


def is_celery_running():
    for proc in psutil.process_iter(['pid', 'name']):
        if 'celery' in proc.name():
            return True
    return False


def start_celery():
    # 使用Python代码启动Celery
    subprocess.Popen(["celery", "-A", "celery_tasks.main", "worker", "-l", "info", "-P", "eventlet"])  # 以示例的方式启动Celery
    # time.sleep(1)  # 等待一段时间以确保Celery已经启动


# 在Django启动后再次检测并启动Celery
if not is_celery_running():
    start_celery()


# 下面为ES代码
def is_elasticsearch_running():
    es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
    return es.ping()


def start_elasticsearch():
    # 使用subprocess库执行Elasticsearch的启动命令
    if platform.system() == 'Windows':
        # Windows系统下使用STARTUPINFO来隐藏命令提示符窗口
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        subprocess.Popen([r"C:\Users\wjj15\Desktop\elk\elasticsearch-7.10.0-windows-x86_64\elasticsearch-7.10.0\bin\elasticsearch.bat"],
                         startupinfo=info, close_fds=True)  # creationflags=subprocess.DETACHED_PROCESS, close_fds=True
    else:
        # Linux和Unix系统下使用nohup命令来后台运行
        subprocess.Popen(["nohup", "/path/to/elasticsearch/bin/elasticsearch", "&"])
    time.sleep(12)


# 在Django启动时检测并启动Elasticsearch
if not is_elasticsearch_running():
    start_elasticsearch()
